﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace tiDE.Assembly
{
    public class Assembler
    {
        /// <summary>
        /// Strips comments from a single line of code
        /// </summary>
        /// <param name="Line"></param>
        public static string StripComments(string Code)
        {
            Code = Code.Trim();
            bool isInString = false, isInChar = false;
            //I'm presuming this is meant to temporarily
            //override the instance variable
            bool MultilineComment = false;
            if (MultilineComment)
            {
                if (Code.Contains("*/"))
                {
                    MultilineComment = false;
                    return Code.Substring(Code.IndexOf("*/") + 2);
                }
                return "";
            }
            if (Code.StartsWith(";") || Code.StartsWith("//"))
                return "";
            for (int i = 0; i < Code.Length; i++)
            {
                if (Code[i] == ';' && !isInString && !isInChar)
                {
                    Code = Code.Remove(i);
                    return Code;
                }
                if (i + 1 < Code.Length && Code[i] == '/' && Code[i + 1] == '/')
                {
                    Code = Code.Remove(i);
                    return Code;
                }
                if (i + 1 < Code.Length && Code[i] == '/' && Code[i + 1] == '*')
                {
                    int end = Code.Length - i;
                    if (Code.Contains("*/"))
                    {
                        end = Code.IndexOf("*/") - i + 2;
                    }
                    else
                        MultilineComment = true;
                    Code = Code.Remove(i, end);
                    return Code;
                }
                if (Code[i] == '"' && !isInChar)
                {
                    isInString = !isInString;
                }
                if (Code[i] == '\'' && !isInString)
                {
                    isInChar = !isInChar;
                }
            }
            return Code;
        }
    }
}
